<template>
  <page-header title="订单详情" background="#F7F0E6"></page-header>
  <view class="order-detail">
    <!-- 订单状态 -->
    <view class="status-box">
      <view class="text">
        <block v-if="status === 1">
          <view class="status">
            等待付款
          </view>
          <view class="des">
            请您在{{ hou }}:{{ min }}:{{ sec }}内付款，逾期订单将取消
          </view>
        </block>
        <block v-else>
          <view class="status">
            {{ ['', '', '等待发货', '等待收货', '', '已完成', '已取消'][status] }}
          </view>
          <view class="des">
            {{ ['', '', '商家还未发货，请您耐心等待', '商品正在运输中，请您耐心等待', '', '感谢您的购买，欢迎下次光临', '您的订单已成功取消'][status] }}
          </view>
        </block>
      </view>
    </view>

    <!-- 地址 -->
    <view class="address">
      <image class="icon" src="../../static/img/location-submit.png"></image>
      <view v-if="orderAddr">
        <view class="group">
          <view class="name">{{ orderAddr.consignee }}
            <text class="mobile">{{ orderAddr.mobile }}
            </text>
          </view>
          <view class="address-name">{{ orderAddr.city + orderAddr.area + orderAddr.addr }}</view>
        </view>
      </view>
      <block v-else>
        用户未选择地址
      </block>
    </view>


    <!-- 商品 -->
    <view class="prods-box">
      <block v-for="(prodItem, prodIdx) in orderItems" :key="prodIdx">
        <view class="prod-item" @tap="toProdDetail(prodItem.spuId)">
            <!-- <view class="prod-item" > -->
          <image class="background" :src="addDomain('/static/cart-item.png')"></image>
          <view class="content">
            <view class="header">
              <image class="icon" src="/static/images/shop.png" />
              {{ shopName }}
              <uni-icons class="right" type="right" color="white"></uni-icons>
            </view>
            <view class="body">
              <image class="left" :src="prodItem.pic" mode="aspectFill"></image>
              <view class="right">
                <view class="text-overflow-clamp-2"> {{ prodItem.spuName }}</view>
                <view class="sku">
                  <view class="skuItem">[{{ prodItem.skuName }}]</view>
                </view>
                <view class="price-box">
                  <price-point :price="prodItem.spuTotalAmount" :point="prodItem.pointPrice" :size="30"></price-point>
                  <view>x{{ prodItem.count }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </block>
    </view>

    <view class="qrcode" v-if="Data.code">
      <uv-qrcode ref="qrcode" :value="Data.code"></uv-qrcode>
      <view class="text">核销码
        <text class="code">{{ Data.code }}</text>
      </view>
    </view>

    <view class="order-info">
      <view class="post-item">
        <view class="item-box">
          <view class="item">
            <view class="tit">
              订单金额：
            </view>
            <view class="text">
              <price-point :point="Data.totalPointPrice" :price="Data.total"></price-point>
            </view>
          </view>
          <view class="item">
            <view class="tit">
              订单编号：
            </view>
            <view class="text">
              {{ orderId }}
            </view>
            <view class="copy" @tap="copy">
              复制
            </view>
          </view>
          <view class="item">
            <view class="tit">
              下单时间：
            </view>
            <view class="text">
              {{ createTime }}
            </view>
          </view>
          <view class="item">
            <view class="tit">
              配送方式：
            </view>
            <view class="text">
              {{ ['', '普通快递', '顺丰快递', '无需快递', '同城配送'][deliveryType] }}
            </view>
          </view>
          <view class="item" v-if="Data.trackId">
            <view class="tit">
              快递单号：
            </view>
            <view class="text">
              {{ trackId }}
            </view>
            <view class="copy" @tap="copyTrackId()">
              复制
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部 -->
    <view class="foot-box">
      <!-- <view class="del-order">删除订单</view> -->
      <!-- 已完成或已取消才出现 -->
      <view class="btn-box">
        <!-- 待付款时出现 -->
        <view v-if="status == 1" class="btn btn-r" @tap="payNow">
          立即支付
        </view>
        <view v-if="status == 1" class="btn btn-r" @tap="payErr">
          我已完成支付
        </view>
        <!-- 待发货时出现 -->
        <view v-if="status == 3" class="btn btn-r" @tap="orderOperation(2)">
          确认收货
        </view>
        <!-- 待收货时出现 -->
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    reactive
  } from 'vue'
  import uniCopy from '../../js_sdk/uni-copy'
  import {
    onHide,
    onShow,
    onUnload
  } from '@dcloudio/uni-app';
  const Data = reactive({
    orderId: '',
    trackId: '',
    total: 0,
    totalPointPrice: 0,
    userAddrDto: {},
    remarks: '',
    orderItems: [],
    idCardList: [],
    createTime: '',
    status: 0,
    productTotalAmount: '',
    transfee: '',
    freeTransfee: '',
    reduceAmount: '',
    orderType: 0,
    shopName: '',
    canRefund: '',
    canAllRefund: '',
    payType: '',
    deliveryType: 3, // 配送类型 3：无需快递
    orderScore: '',
    orderAddr: {},
    code: '',
    hou: '', // 时
    min: '', // 分
    sec: '' // 秒
  })
  const {
    orderId,
    trackId,
    total,
    totalPointPrice,
    idCardList,
    orderItems,
    createTime,
    status,
    shopName,
    deliveryType,
    orderAddr,
    code,
    hou,
    min,
    sec
  } = toRefs(Data)

  onLoad((options) => {
    if (options.orderId) {
      Data.orderId = options.orderId
    }
  })

  onShow(() => {
    // 请求订单详情数据
    loadOrderDetail()
  })

  onUnload(() => {
    clearTimeout(Data.timer)
  })

  onHide(() => {
    clearTimeout(Data.timer)
  })

  /**
   * 加入购物车
   */
  const addCart = (spuId, skuId, count) => {
    const params = {
      url: '/mall4cloud_product/a/shop_cart/change_item',
      method: 'POST',
      data: {
        skuId,
        spuId,
        count
      }
    }
    http.request(params).then(() => {
      uni.showToast({
        title: '加入购物车成功~',
        duration: 2000,
        icon: 'none'
      })
    })
  }

  /**
   * 立即支付
   */
  const payNow = () => {
    uni.navigateTo({
      url: '/pages/payment/payment?orderIds=' + Data.orderId
    })
  }
  /**
   * 支付出错，查询订单支付状态
   */
  const payErr = () => {
    const params = {
      url: '/mall4cloud_payment/pay/isPay/' + Data.orderId,
      method: 'GET'
    }
    http.request(params).then((res) => {
      if (res) {
        uni.redirectTo({
          url: `/pages/payment-result/payment-result?sts=1&orderIds=${Data.orderIds}`
        })
      } else {
        uni.showToast({
          title: '暂时未查询到支付完成信息',
          duration: 2000,
          icon: 'none'
        })
      }
    })
  }

  /**
   * 订单操作按钮
   * @param {number} operType 0:取消订单; 1删除订单; 2确认收货
   */
  const orderOperation = (operType) => {
    let url = ''
    let reqMethod = ''
    if (operType === 0) {
      url = '/mall4cloud_order/p/myOrder/'
      reqMethod = 'DELETE'
    } else if (operType === 1) {
      url = '/mall4cloud_order/p/myOrder/cancel/'
      reqMethod = 'PUT'
    } else if (operType === 2) {
      url = '/mall4cloud_order/p/myOrder/receipt/'
      reqMethod = 'PUT'
    }
    url = url + Data.orderId
    const params = {
      url,
      method: reqMethod
    }
    http.request(params).then(() => {
      uni.showToast({
        title: '操作成功',
        duration: 2000
      })
      setTimeout(() => {
        loadOrderDetail()
      }, 1000)
    })
  }

  /**
   * 跳转商品详情
   */
  const toProdDetail = (spuId) => {
    uni.navigateTo({
      url: '/pages/shop-detail/shop-detail?spuId=' + spuId
    })
  }

  /**
   * 加载订单数据
   */
  const loadOrderDetail = () => {
    const params = {
      url: '/mall4cloud_order/p/myOrder/order_detail',
      method: 'GET',
      data: {
        orderId: Data.orderId
      }
    }
    http.request(params).then(res => {
      Data.orderAddr = res.orderAddr
      Data.trackId = res.trackId
      Data.total = res.total
      Data.totalPointPrice = res.totalPointPrice
      Data.userAddrDto = res.userAddrDto
      Data.remarks = res.remarks
      Data.orderItems = res.orderItems
      Data.idCardList = Data.orderItems[0].skuIdCardList || []
      Data.createTime = res.createTime
      Data.status = res.status
      Data.transfee = res.transfee
      Data.freeTransfee = res.freeTransfee // 运费减免
      Data.reduceAmount = res.reduceAmount
      Data.orderType = res.orderType
      Data.shopName = res.shopName
      Data.canRefund = res.canRefund
      Data.canAllRefund = res.canAllRefund
      Data.payType = res.payType
      Data.deliveryType = res.deliveryType // 配送类型 1:快递 2:自提 3：无需快递
      Data.orderScore = res.orderScore // 整单使用积分
      if (Data.status == 1)
        getCountDown()
      if (Data.status != 2) return
      http.request({
        url: '/mall4cloud_order/p/myOrder/order_verify_code',
        method: 'GET',
        data: {
          orderId: Data.orderId
        }
      }).then(res => {
        Data.code = res
      })
    })
  }

  /**
   * 复制订单号
   */
  const copy = () => {
    uniCopy({
      content: Data.orderId,
      success: (res) => {
        uni.showToast({
          title: res,
          icon: 'none'
        })
      },
      error: (e) => {
        uni.showToast({
          title: e,
          icon: 'none',
          duration: 3000
        })
      }
    })
  }
  /**
   * 复制物流订单号
   */
  const copyTrackId = () => {
    uniCopy({
      content: Data.trackId,
      success: (res) => {
        uni.showToast({
          title: res,
          icon: 'none'
        })
      },
      error: (e) => {
        uni.showToast({
          title: e,
          icon: 'none',
          duration: 3000
        })
      }
    })
  }
  // 添加图片域名
  const addDomain = (path) => {
      const resourcesUrl = import.meta.env.VITE_APP_FILE_URL
    if (!path || /^http?:\/\//.test(path)) {
      return path
    } else {
      return resourcesUrl + path
    }
  }
  /**
   * 生成支付倒计时
   */
  const getCountDown = () => {
    const nowTime = new Date().getTime() // 现在时间（时间戳）
    const endTime = new Date(Data.createTime.replace(/-/g, '/')).getTime() + 60 * 60 * 1000 // 结束时间（时间戳）
    const time = (endTime - nowTime) / 1000 // 距离结束的毫秒数
    // 获取时、分、秒
    let hou = parseInt(time % (60 * 60 * 24) / 3600)
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60)
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60)
    hou = timeFormin(hou)
    min = timeFormin(min)
    sec = timeFormin(sec)
    Data.hou = timeFormat(hou)
    Data.min = timeFormat(min)
    Data.sec = timeFormat(sec)
    // 每1000ms刷新一次
    if (time > 0) {
      Data.countDown = true
      Data.timer = setTimeout(getCountDown, 1000)
    } else {
      Data.countDown = false
      uni.redirectTo({
        url: `/pages/payment-result/payment-result?sts=0&orderIds=${Data.orderIds}`
      })
      // this.$Router.push('/pages/orderList/orderList')
    }
  }
  // 小于10的格式化函数（2变成02）
  const timeFormat = (num) => {
    return num < 10 ? '0' + num : num
  }
  // 小于0的格式化函数（不会出现负数）
  const timeFormin = (num) => {
    return num < 0 ? 0 : num
  }
</script>

<style>
  page {
    background-color: #FFFAF4;
  }
</style>

<style lang="scss" scoped>
  @use "order-detail";
</style>
